package cn.thank.anno;

import java.lang.reflect.Method;
import java.rmi.ServerException;
import java.util.Date;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sun.org.apache.xml.internal.security.keys.content.RetrievalMethod;

import cn.thank.dao.UserDao;
import cn.thank.model.UseAccount;

@Component
@Aspect
public class AccountAnnoHandler {
	@Autowired
	private UserDao userDao;
	
	@Pointcut("@annotation(cn.thank.anno.AccountAnno)")
	private void serviceCut(){}
	
	
	@AfterReturning(pointcut="serviceCut()",returning = "returnVal")
	public void doAfterMethod(JoinPoint point,int returnVal) throws ServerException, NoSuchMethodException, SecurityException{
		
		// 获取注解中方法的名字
		MethodSignature ms = (MethodSignature) point.getSignature();
        Method method = ms.getMethod();
        Method realMethod = point.getTarget().getClass().getDeclaredMethod(point.getSignature().getName(), method.getParameterTypes());
        AccountAnno accountAnno = realMethod.isAnnotationPresent(AccountAnno.class)?realMethod.getAnnotation(AccountAnno.class):null;
        String methodName = accountAnno.method();
        System.out.println(methodName);
//        String m = method.toString();
//        int index = m.lastIndexOf("."); 
//        char[] ch = m.toCharArray(); 
//        String methodName = String.copyValueOf(ch, index + 1, ch.length - index - 1);
//        UseAccount useAccount = userDao.selectByFunction(methodName);
//        if(useAccount != null){
//        	useAccount.setNumbers(useAccount.getNumbers()+1);
//        	useAccount.setUpdatetime(new Date());
//        	userDao.update(useAccount);
//        }else{
        	UseAccount ua = new UseAccount();
        	ua.setNumbers(1);
        	ua.setFunctionName(methodName);
        	ua.setCreatetime(new Date());
        	ua.setResponsetime(returnVal);
        	userDao.insert(ua);
//        }
        
	}
	
}
